package com.meshnetics.gb.type.impl.additional;

import com.meshnetics.gb.type.DataValue;
import com.meshnetics.gb.type.MandatoryFormatter;
import com.meshnetics.gb.type.impl.StringUtils;
import com.meshnetics.gb.type.impl.zcl.AbstractDataType;
import com.meshnetics.gb.type.impl.zcl.AbstractMandatoryFormatter;
import com.meshnetics.gb.util.ByteBufferManager;

/**
 * Base class for data types.
 *
 * @author Yury Aserchev (yaserchev@meshnetics.com)
 *         Date: 27.08.2008 20:58:11
 */
public abstract class BaseDataType extends AbstractDataType {
    private final MandatoryFormatter formatter = new InternalFormatter();

    public BaseDataType(String name) {
        super(new String[]{name});
    }

    public final DataValue valueOf(byte[] value) {
        if (value == null) {
            throw new NullPointerException("parameter value is null");
        }
        return deserialize(ByteBufferManager.wrapBE(value));
    }

    public final DataValue fromObject(Object value) {
        throw new IllegalStateException("not realized");
    }

    public final MandatoryFormatter getMandatoryFormatter() {
        return formatter;
    }
    final class InternalFormatter extends AbstractMandatoryFormatter {
        public InternalFormatter() {
            super(BaseDataType.this);
        }

        public String formatSerializedString(final DataValue value) {
            return StringUtils.toHexString(value.bytesValue());
        }

        public String formatShortLogString(final DataValue value) {
            return value.toString();
        }

        public DataValue valueOf(final String serializedValue) {
            if (serializedValue == null) {
                throw new NullPointerException("parameter serializedValue is null");
            }
            return BaseDataType.this.valueOf(StringUtils.recoverBytesFromHexString(serializedValue, 0,
                    serializedValue.length()));
        }
    }
}
